import {reaction, runInAction} from "mobx"

export function persistToLocalStorage<T>(
    storageKey: string,
    onLoadAction: (data: T) => void,
    getter: () => T,
) {
    const data = localStorage.getItem(storageKey)
    if (data) {
        runInAction(() => {
            onLoadAction(JSON.parse(data))
        })
    }
    reaction(getter, data => {
        if (data) {
            return localStorage.setItem(storageKey, JSON.stringify(data))
        } else {
            return localStorage.removeItem(storageKey)
        }
    })
}
